package com.wct.springSecurity.common;

import com.wct.springSecurity.exception.ParamException;
import com.wct.springSecurity.exception.PermissionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author WEI (Email:changtan20000@163.com)
 * @description 全局异常处理类
 * @date 2020/1/15 21:52
 */

@Slf4j
public class SpringExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 请求的url
        String url = request.getRequestURI();
        ModelAndView mv;
        String defaultMsg = "System error";

        /*
        * .page  .json
        * 项目中要求所有请求json数据，都使用.json结尾
        * 请求页面使用.page结尾
        * */
        // 判断是页面请求还是数据请求
        if (url.endsWith(".json")) {
            // 判断异常类型
            if (ex instanceof PermissionException || ex instanceof ParamException) {
                JsonData result = JsonData.fail(ex.getMessage());
                // jsonView 对应 spring-servlet.xml 中的 jsonView
                mv = new ModelAndView("jsonView", result.toMap());
            } else {
                log.error("unknown json exception, url:" + url, ex);
                JsonData result = JsonData.fail(defaultMsg);
                mv = new ModelAndView("jsonView", result.toMap());
            }
        } else if (url.endsWith(".page")) {
            JsonData result = JsonData.fail(defaultMsg);
            mv = new ModelAndView("exception", result.toMap());
        } else {
            log.error("unknown page exception, url:" + url, ex);
            JsonData result = JsonData.fail(defaultMsg);
            mv = new ModelAndView("jsonView", result.toMap());
        }

        return mv;
    }
}
